import React from 'react';
import { Card, Form, Input, Button, Row, Col, List, Badge, Modal, message } from 'antd';
import { LockOutlined, SafetyOutlined, MobileOutlined, KeyOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { authApi } from '@/api/auth';

const { Password } = Input;
const { confirm } = Modal;

const SecurityPage: React.FC = () => {
  const queryClient = useQueryClient();
  const [form] = Form.useForm();

  // 获取安全设置
  const { data: securityData, isLoading } = useQuery({
    queryKey: ['securitySettings'],
    queryFn: async () => {
      const response = await authApi.getUserProfile();
      return response;
    },
  });

  // 修改密码
  const changePasswordMutation = useMutation({
    mutationFn: authApi.changePassword,
    onSuccess: () => {
      message.success('密码修改成功！');
      form.resetFields();
      queryClient.invalidateQueries({ queryKey: ['securitySettings'] });
    },
    onError: () => {
      message.error('密码修改失败，请重试');
    },
  });

  // 验证密码强度
  const validatePasswordStrength = (_: any, value: string) => {
    if (!value) {
      return Promise.reject('请输入新密码');
    }

    if (value.length < 8) {
      return Promise.reject('密码长度至少8位');
    }

    if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(value)) {
      return Promise.reject('密码必须包含大小写字母和数字');
    }

    if (!/[!@#$%^&*(),.?":{}|<>]/.test(value)) {
      return Promise.reject('密码必须包含特殊字符');
    }

    return Promise.resolve();
  };

  // 表单提交
  const handleSubmit = async (values: { oldPassword: string; newPassword: string }) => {
    try {
      await changePasswordMutation.mutateAsync({
        oldPassword: values.oldPassword,
        newPassword: values.newPassword,
      });
    } catch (error) {
      // 密码修改失败
    }
  };

  // 显示删除确认对话框
  const showDeleteConfirm = () => {
    confirm({
      title: '确认删除账户？',
      icon: <ExclamationCircleOutlined />,
      content: '删除账户后，您的所有数据将被永久删除，此操作不可恢复！',
      okText: '确认删除',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        message.info('账户删除功能请联系管理员');
      },
      onCancel() {
        // 取消删除账户
      },
    });
  };

  // 安全等级计算
  const calculateSecurityLevel = () => {
    let level = 0;

    if (securityData) {
      // 基础密码
      level += 20;

      // 双重验证
      if (securityData.twoFactorEnabled) {
        level += 30;
      }

      // 手机绑定
      if (securityData.mobile) {
        level += 20;
      }

      // 邮箱验证
      if (securityData.emailVerified) {
        level += 15;
      }

      // 最近登录安全
      if (securityData.lastLoginSecure) {
        level += 15;
      }
    }

    return level;
  };

  const securityLevel = calculateSecurityLevel();
  const securityLevelText = securityLevel >= 80 ? '高' : securityLevel >= 50 ? '中' : '低';
  const securityLevelColor = securityLevel >= 80 ? 'green' : securityLevel >= 50 ? 'orange' : 'red';

  const securityItems = [
    {
      title: '登录密码',
      description: '用于登录系统的密码',
      status: '已设置',
      statusType: 'success' as const,
      action: '修改',
      icon: <LockOutlined />,
    },
    {
      title: '双重验证',
      description: '通过手机验证码或应用验证器进行二次验证',
      status: securityData?.twoFactorEnabled ? '已启用' : '未启用',
      statusType: securityData?.twoFactorEnabled ? 'success' as const : 'warning' as const,
      action: securityData?.twoFactorEnabled ? '管理' : '启用',
      icon: <SafetyOutlined />,
    },
    {
      title: '手机绑定',
      description: '用于接收验证码和安全提醒',
      status: securityData?.mobile ? '已绑定' : '未绑定',
      statusType: securityData?.mobile ? 'success' as const : 'warning' as const,
      action: securityData?.mobile ? '更换' : '绑定',
      icon: <MobileOutlined />,
    },
    {
      title: '邮箱验证',
      description: '用于接收重要通知和安全提醒',
      status: securityData?.emailVerified ? '已验证' : '未验证',
      statusType: securityData?.emailVerified ? 'success' as const : 'warning' as const,
      action: securityData?.emailVerified ? '管理' : '验证',
      icon: <KeyOutlined />,
    },
  ];

  return (
    <div style={{ height: '100%', width: '100%', overflow: 'auto' }}>
      <Card title="安全设置" loading={isLoading} style={{ height: 'auto' }}>
        {/* 安全等级 */}
        <Card size="small" style={{ marginBottom: 16 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div>
              <h3 style={{ margin: 0, marginBottom: 8 }}>安全等级</h3>
              <p style={{ margin: 0, color: '#666' }}>
                根据您的安全设置，当前账户安全等级为
                <Badge
                  count={securityLevelText}
                  style={{ backgroundColor: securityLevelColor, marginLeft: 8 }}
                />
              </p>
            </div>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 24, fontWeight: 'bold', color: securityLevelColor }}>
                {securityLevel}%
              </div>
              <div style={{ fontSize: 12, color: '#666' }}>安全评分</div>
            </div>
          </div>
        </Card>

        {/* 安全设置项 */}
        <Card title="安全设置" size="small" style={{ marginBottom: 16 }}>
          <List
            itemLayout="horizontal"
            dataSource={securityItems}
            renderItem={(item) => (
              <List.Item>
                <List.Item.Meta
                  avatar={<div style={{ fontSize: 24, color: '#1890ff' }}>{item.icon}</div>}
                  title={
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      {item.title}
                      <Badge
                        count={item.status}
                        style={{
                          backgroundColor: item.statusType === 'success' ? '#52c41a' : '#faad14',
                          fontSize: 12,
                        }}
                      />
                    </div>
                  }
                  description={item.description}
                />
                <Button type="link" size="small">
                  {item.action}
                </Button>
              </List.Item>
            )}
          />
        </Card>

        {/* 修改密码 */}
        <Card title="修改密码" size="small" style={{ marginBottom: 16 }}>
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmit}
            autoComplete="off"
          >
            <Row gutter={16}>
              <Col xs={24} sm={12}>
                <Form.Item
                  label="当前密码"
                  name="oldPassword"
                  rules={[{ required: true, message: '请输入当前密码' }]}
                >
                  <Password placeholder="请输入当前密码" />
                </Form.Item>
              </Col>
              <Col xs={24} sm={12}>
                <Form.Item
                  label="新密码"
                  name="newPassword"
                  rules={[
                    { required: true, message: '请输入新密码' },
                    { validator: validatePasswordStrength }
                  ]}
                >
                  <Password placeholder="请输入新密码" />
                </Form.Item>
              </Col>
              <Col xs={24} sm={12}>
                <Form.Item
                  label="确认新密码"
                  name="confirmPassword"
                  dependencies={['newPassword']}
                  rules={[
                    { required: true, message: '请确认新密码' },
                    ({ getFieldValue }) => ({
                      validator(_, value) {
                        if (!value || getFieldValue('newPassword') === value) {
                          return Promise.resolve();
                        }
                        return Promise.reject(new Error('两次输入的密码不一致'));
                      },
                    }),
                  ]}
                >
                  <Password placeholder="请确认新密码" />
                </Form.Item>
              </Col>
            </Row>
            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                loading={changePasswordMutation.isPending}
                style={{ marginRight: 8 }}
              >
                修改密码
              </Button>
              <Button onClick={() => form.resetFields()}>
                重置
              </Button>
            </Form.Item>
          </Form>
        </Card>

        {/* 危险操作 */}
        <Card title="危险操作" size="small">
          <div style={{ padding: 16, backgroundColor: '#fff2f0', borderRadius: 4, marginBottom: 16 }}>
            <h4 style={{ color: '#ff4d4f', margin: 0 }}>警告：以下操作不可恢复</h4>
            <p style={{ margin: '8px 0 0 0', color: '#666' }}>
              请谨慎操作，删除账户后将无法恢复您的数据。
            </p>
          </div>
          <Button danger onClick={showDeleteConfirm}>
            删除账户
          </Button>
        </Card>
      </Card>
    </div>
  );
};

export default SecurityPage;